package com.boarsoft.boar.soagov.app.biz;

import java.util.List;

import org.hibernate.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.soagov.app.AppSvcBiz;
import com.boarsoft.boar.soagov.entity.AppSvc;
import com.boarsoft.boar.soagov.entity.SvcInfo;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("appSvcBiz")
public class AppSvcBizImpl extends SimpleBizImpl implements AppSvcBiz {
	@Override
	@Transactional
	public void add(String appId, String[] svcIds) {
		StringBuilder sb = new StringBuilder().append("from ")//
				.append(AppSvc.class.getName()).append(" where appId=:appId and svcId=:svcId");
		// 关联库包与服务
		Query<AppSvc> asQry = dao.createQuery(AppSvc.class, sb.toString());
		asQry.setParameter("appId", appId);
		for (String svcId : svcIds) {
			asQry.setParameter("svcId", svcId);
			AppSvc as = asQry.uniqueResult();
			if (as == null) {
				as = new AppSvc();
				as.setSvcId(svcId);
				as.setAppId(appId);
				dao.save(as);
			}
		}
	}

	@Override
	@Transactional
	public void remove(String appId, String[] svcIds) {
		StringBuilder sb = new StringBuilder()//
				.append("delete from ").append(AppSvc.class.getName())//
				.append(" where appId=:appId and svcId=:svcId");
		Query<?> q = dao.createQuery(sb.toString());
		q.setParameter("appId", appId);
		for (String svcId : svcIds) {
			q.setParameter("svcId", svcId);
			q.executeUpdate();
		}
	}

	@Override
	@Transactional(readOnly = true)
	public PagedResult<SvcInfo> list(String appId, String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(AppInfo.class.getName());
		sb.append(" a join a.svcs s where a.id='").append(appId).append("'");
		if (Util.strIsNotEmpty(key)) {
			sb.append("and (s.code like '%").append(key);
			sb.append("%' or s.name like '%").append(key);
			sb.append("%')");
		}
		int total = dao.getTotal("select count(s.id)".concat(sb.toString()));
		if (Util.strIsNotEmpty(orderBy)) {
			sb.append(" order by s.").append(orderBy);
		} else {
			sb.append(" order by s.name");
		}
		List<SvcInfo> lt = dao.list("select s".concat(sb.toString()), pageNo, pageSize);
		return new PagedResult<SvcInfo>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional(readOnly = true)
	public List<SvcInfo> list(String appId, short status) {
		String sb = "and appId='" + appId + "' and status=" + status;
		return dao.list(SvcInfo.class, sb);
	}

	@Override
	@Transactional(readOnly = true)
	public List<SvcInfo> list(String appId) {
		return dao.list(SvcInfo.class, "and appId='" + appId + "'");
	}
}